package com.sgb.packers.view.activity;

import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.router.PathTeam;
import com.sgb.packers.R;
import com.sgb.packers.databinding.PackersActivityWorkAccountBinding;
import com.sgb.packers.entity.ProjectEntity;
import com.sgb.packers.entity.WorkTakeEntity;
import com.sgb.packers.view.adapter.WorkAccountAdapter;
import com.sgb.packers.viewmodel.WorkAccountViewModel;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.MapUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author 王彬臣
 * @date 2021/11/24
 * @Description 记工流水目录
 */
@Route(path = PathTeam.WorkAccountActivity)
public class WorkAccountActivity extends BaseActivity<WorkAccountViewModel, PackersActivityWorkAccountBinding> {
    private WorkAccountAdapter mAdapter;
    private final List<WorkTakeEntity> mList = new ArrayList<>();
    private List<ProjectEntity> mProject;
    private int mProjectPopPosition;
    private TimePickerView timeEndPicker;

    @Autowired(name = "projectNo", desc = "项目的no")
    String projectNo;

    @Autowired(name = "projectName", desc = "项目名称")
    String projectName;

    @Autowired(name = "position", desc = "项目名称")
    int position;

    private int year, month;
    private int page;

    @Override
    protected int layoutId() {
        return R.layout.packers_activity_work_account;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(WorkAccountViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setOnClick(this);
        mBinding.actionBar.setOnBackClickListener(v -> finish());
        mBinding.actionBar.setMenuFunctionClick(v -> ActivityJump.startActivity(PathTeam.WorkStatisticsActivity));
        mBinding.rvList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new WorkAccountAdapter(mList);
        DividerDecoration.builder(this)
                .color(ContextCompat.getColor(WorkAccountActivity.this, R.color.color_f5f5f5))
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvList);
        mAdapter.bindToRecyclerView(mBinding.rvList);
        mAdapter.setEmptyView(R.layout.packers_empty_views);
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadData(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData(false);
            }
        });
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        mBinding.tvMonthName.setText(String.format("%s年%s月", "" + year, "" + month));
        mViewModel.getProject(new MapUtils().pair2Map(Pair.create("type", 1)));
        loadData(false);
        initObserve();
    }

    private void initObserve() {
        mViewModel.mGetProjectLiveData.observe(this, projectEntities -> {
            mProject = projectEntities;
            if (mProject != null && mProject.size() > 0) {
                mBinding.tvProjectName.setText(projectName);
                loadData(false);
            }
        });
        mViewModel.mTakeWorkAccountLiveData.observe(this, listListResponse -> {
            mBinding.refreshLayout.finishRefresh();
            mBinding.refreshLayout.finishLoadMore();
            if (page == 1) {
                mList.clear();
            }
            if (listListResponse.getList() != null) {
                mList.addAll(listListResponse.getList());
            }
            mAdapter.notifyDataSetChanged();
            if (listListResponse.getCurrentPage() < listListResponse.getTotalPage()) {
                mBinding.refreshLayout.resetNoMoreData();
            } else {
                mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });
    }

    @Override
    protected void onMultiClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_month) {
            if (timeEndPicker == null) {
                timeEndPicker = new TimePickerBuilder(this, (date, v1) -> {
                    Calendar cal1 = Calendar.getInstance();
                    cal1.setTime(date);
                    year = cal1.get(Calendar.YEAR);
                    month = cal1.get(Calendar.MONTH) + 1;
                    mBinding.tvMonthName.setText(DateUtils.date2Timestamp(date));
                    loadData(false);
                }).setTitleText("选择年月").setRangDate(null, Calendar.getInstance()).setType(new boolean[]{true, true, false, false, false, false}).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            }
            timeEndPicker.show();
        } else if (id == R.id.rl_project) {
            if (mProject != null && mProject.size() > 0) {
                if (mProjectPopPosition == 0){
                    mProjectPopPosition = position;
                }

                OptionsPickerView mProjectPop = new OptionsPickerBuilder(this, (options1, options2, options3, view) -> {
                    mBinding.tvProjectName.setText(mProject.get(options1).getProjectName());
                    mProjectPopPosition = options1;
                    projectNo = mProject.get(options1).getNo();
                    loadData(false);
                }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
                mProjectPop.setPicker(mProject);
                mProjectPop.setSelectOptions(mProjectPopPosition);
                mProjectPop.setTitleText("选择项目");
                mProjectPop.show();
            } else {
                MToast.showToast(this, "没有项目");
            }
        }
    }

    private void loadData(boolean isLoadMore) {
        if (isLoadMore){
            page++;
        }else {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>(6);
        map.put("page", page);
        map.put("projectNo", projectNo);
        map.put("limit", 20);
        map.put("type", 1);
        map.put("year", year);
        String month1 = month > 10 ? String.valueOf(month) : String.format(Locale.CHINA, "0%d", month);
        map.put("month", month1);
        mViewModel.takeWorkAccount(map);
    }
}
